package com.huiquan.icd.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.RespHeaderUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.icd.dao.IcdDiseaseWeatherDao;
import com.huiquan.icd.domain.BaseEntity;
import com.huiquan.icd.domain.IcdAgeSexMonthDiease;
import com.huiquan.icd.domain.IcdSeasonWeather;
import com.huiquan.icd.domain.IcdWeatherDisease;
import com.huiquan.medicine.dao.MedicineDao;

/**
 * 疾病与天气 service
 * 
 * @author leo
 * @time 2017年4月7日 下午2:47:58
 */
@Service
public class IcdDiseaseWeatherService extends BaseService {

	@Autowired
	private IcdDiseaseWeatherDao dao;

	@Autowired
	private MedicineDao medicineDao;

	/**
	 * 查看疾病与天气列表
	 * 
	 * @param tabid
	 * @param start
	 * @param keyword
	 * @param status
	 *            1-season_weather，2-weather_disease，3-age_sex_month_disease
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> viewDiseaseWeatherList(int start,
			String keyword, int status, String countPerPageStr) {
		Map<String, Object> param = new HashMap<>();
		if (keyword != null && !keyword.isEmpty()) {
			param.put("keyword", "%" + keyword + "%");
		}
		int totalSize = dao.selectListSize(param, status);
		Map<String, Integer> pageNo = new HashMap<>();
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "",
					countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");
		List<BaseEntity> list = new ArrayList<>();
		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = (List<BaseEntity>) dao.selectList(param, status);
		}
		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "名称");

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start,
				startIndex, endPage, list, null);
		map.put("showSearch", showSearch);
		map.put("status", status);
		return map;
	}

	/**
	 * 更新数据
	 * 
	 * @param user
	 * @param params
	 * @param status
	 *            1-season_weather，2-weather_disease，3-age_sex_month_disease
	 * @return
	 */
	public ReturnData updateData(User user, Map<String, String> params,
			int status) {
		int id = Integer.valueOf(params.get("id"));
		if (status == 1) {
			IcdSeasonWeather entity = dao.selectIcdSeasonWeatherById(id);
			if (StringUtils.isNotEmpty(params.get("season"))) {
				entity.setSeason(params.get("season"));
			}
			if (StringUtils.isNotEmpty(params.get("disease"))) {
				if (medicineDao.selectIcdDiseaseCountByName(params
						.get("disease")) < 1) {
					Map<String, Object> map = new HashMap<>();
					ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					returnCode.setDesc("更新失败，" + params.get("disease")
							+ "  在疾病维表中不存在");
					return new ReturnData(returnCode, map);
				}
				entity.setDisease(params.get("disease"));
			}
			if (StringUtils.isNotEmpty(params.get("priority"))) {
				entity.setPriority(Integer.valueOf(params.get("priority")));
			}
			if (StringUtils.isNotEmpty(params.get("age"))) {
				entity.setAge(params.get("age"));
			}
			entity.setModifierId(user.getUserId());
			entity.setModifierName(user.getRealName());
			dao.updateIcdSeasonWeather(entity);
		} else if (status == 2) {
			IcdWeatherDisease entity = dao.selectIcdWeatherDiseaseById(id);
			if (StringUtils.isNotEmpty(params.get("season"))) {
				entity.setSeason(params.get("season"));
			}
			if (StringUtils.isNotEmpty(params.get("ruleType"))) {
				entity.setRuleType(params.get("ruleType"));
			}
			if (StringUtils.isNotEmpty(params.get("subType"))) {
				entity.setSubType(params.get("subType"));
			}
			if (StringUtils.isNotEmpty(params.get("value"))) {
				entity.setValue(Integer.valueOf(params.get("value")));
			}
			if (StringUtils.isNotEmpty(params.get("disease"))) {
				if (medicineDao.selectIcdDiseaseCountByName(params
						.get("disease")) < 1) {
					Map<String, Object> map = new HashMap<>();
					ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					returnCode.setDesc("更新失败，" + params.get("disease")
							+ "  在疾病维表中不存在");
					return new ReturnData(returnCode, map);
				}
				entity.setDisease(params.get("disease"));
			}
			if (StringUtils.isNotEmpty(params.get("priority"))) {
				entity.setPriority(Integer.valueOf(params.get("priority")));
			}
			if (StringUtils.isNotEmpty(params.get("age"))) {
				entity.setAge(params.get("age"));
			}
			if (StringUtils.isNotEmpty(params.get("tips"))) {
				entity.setTips(params.get("tips"));
			}
			entity.setModifierId(user.getUserId());
			entity.setModifierName(user.getRealName());
			dao.updateIcdWeatherDisease(entity);
		} else if (status == 3) {
			IcdAgeSexMonthDiease entity = dao
					.selectIcdAgeSexMonthDieaseById(id);
			if (StringUtils.isNotEmpty(params.get("age1"))) {
				entity.setAge1(Integer.valueOf(params.get("age1")));
			}
			if (StringUtils.isNotEmpty(params.get("age2"))) {
				entity.setAge2(Integer.valueOf(params.get("age2")));
			}
			if (StringUtils.isNotEmpty(params.get("sex"))) {
				entity.setSex(Integer.valueOf(params.get("sex")));
			}
			if (StringUtils.isNotEmpty(params.get("month"))) {
				entity.setMonth(Integer.valueOf(params.get("month")));
			}
			if (StringUtils.isNotEmpty(params.get("di"))) {
				if (medicineDao.selectIcdDiseaseCountByName(params.get("di")) < 1) {
					Map<String, Object> map = new HashMap<>();
					ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					returnCode.setDesc("更新失败，" + params.get("di")
							+ "  在疾病维表中不存在");
					return new ReturnData(returnCode, map);
				}
				entity.setDi(params.get("di"));
			}
			if (StringUtils.isNotEmpty(params.get("rank"))) {
				entity.setRank(Integer.valueOf(params.get("rank")));
			}
			entity.setModifierId(user.getUserId());
			entity.setModifierName(user.getRealName());
			dao.updateIcdAgeSexMonthDieaser(entity);
		}
		return ReturnUtil.success();
	}

	/**
	 * 删除一条数据
	 * 
	 * @param id
	 * @param status
	 *            1-season_weather，2-weather_disease，3-age_sex_month_disease
	 * @return
	 */
	public ReturnData deleteData(int id, int status) {
		if (status == 1) {
			dao.deleteIcdSeasonWeatherById(id);
		} else if (status == 2) {
			dao.delecteIcdWeatherDiseaseById(id);
		} else if (status == 3) {
			dao.deleteIcdAgeSexMonthDieaseById(id);
		}
		return ReturnUtil.success();
	}

	/**
	 * 导入数据
	 * 
	 * @param user
	 * @param file
	 * @param status
	 *            1-season_weather，2-weather_disease，3-age_sex_month_disease
	 * @return
	 * @throws IOException
	 */
	public ReturnData importData(User user, MultipartFile file, int status)
			throws IOException {
		LOGGER.info("batch begin!");
		InputStream excelIn = file.getInputStream();
		InputStreamReader read = new InputStreamReader(excelIn, "UTF-8"); // 考虑到文本编码
		Workbook workbook = new XSSFWorkbook(excelIn);
		Sheet sheet = workbook.getSheetAt(0);
		Map<String, String> params = null;
		// 行数
		if (status == 1) {
			List<IcdSeasonWeather> insertList = new ArrayList<>();
			for (Row row : sheet) {
				if (medicineDao.selectIcdDiseaseCountByName(row.getCell(1)
						.getStringCellValue()) > 0) {
					String season = "";
					String disease = "";
					int priority = 0;
					String age = "";
					for (Cell cell : row) {
						row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(2).setCellType(Cell.CELL_TYPE_NUMERIC);
						row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
						season = row.getCell(0).getStringCellValue();
						disease = row.getCell(1).getStringCellValue();
						priority = (int) row.getCell(2).getNumericCellValue();
						age = row.getCell(3).getStringCellValue();
					}
					IcdSeasonWeather value = new IcdSeasonWeather();
					value.setSeason(season);
					value.setDisease(disease);
					value.setPriority(priority);
					value.setAge(age);
					value.setModifierId(user.getUserId());
					value.setModifierName(user.getRealName());
					insertList.add(value);
				} else {
					Map<String, Object> map = new HashMap<>();
					ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					returnCode.setDesc("导入失败，"
							+ row.getCell(1).getStringCellValue()
							+ "  在疾病维表中不存在");
					return new ReturnData(returnCode, map);
				}
			}
			dao.deleteIcdSeasonWeather();
			dao.batchInsertIcdSeasonWeather(insertList);
		} else if (status == 2) {
			List<IcdWeatherDisease> insertList = new ArrayList<>();
			for (Row row : sheet) {
				if (medicineDao.selectIcdDiseaseCountByName(row.getCell(4)
						.getStringCellValue()) > 0) {
					String season = "";
					String ruleType = "";
					String subType = "";
					int value = 0;
					String disease = "";
					int priority = 0;
					String age = "";
					String tips = "";
					for (Cell cell : row) {
						row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(3).setCellType(Cell.CELL_TYPE_NUMERIC);
						row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(5).setCellType(Cell.CELL_TYPE_NUMERIC);
						row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
						season = row.getCell(0).getStringCellValue();
						ruleType = row.getCell(1).getStringCellValue();
						subType = row.getCell(2).getStringCellValue();
						value = (int) row.getCell(3).getNumericCellValue();
						disease = row.getCell(4).getStringCellValue();
						priority = (int) row.getCell(5).getNumericCellValue();
						age = row.getCell(6).getStringCellValue();
						tips = row.getCell(7).getStringCellValue();
					}
					IcdWeatherDisease value1 = new IcdWeatherDisease();
					value1.setSeason(season);
					value1.setRuleType(ruleType);
					value1.setSubType(subType);
					value1.setValue(value);
					value1.setDisease(disease);
					value1.setPriority(priority);
					value1.setAge(age);
					value1.setTips(tips);
					value1.setModifierId(user.getUserId());
					value1.setModifierName(user.getRealName());
					insertList.add(value1);
				} else {
					Map<String, Object> map = new HashMap<>();
					ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
					returnCode.setDesc("导入失败，"
							+ row.getCell(4).getStringCellValue()
							+ "  在疾病维表中不存在");
					String a = row.getCell(1).getStringCellValue();
					int b = medicineDao.selectIcdDiseaseCountByName(row
							.getCell(4).getStringCellValue());
					return new ReturnData(returnCode, map);
				}
			}
			dao.delecteIcdWeatherDisease();
			dao.batchInsertIcdWeatherDisease(insertList);
		} else if (status == 3) {
			params = new HashMap<>();
			for (Row row : sheet) {
				for (Cell cell : row) {
					row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
					params.put("age1", row.getCell(0).getStringCellValue());
					row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
					params.put("age2", row.getCell(1).getStringCellValue());
					row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
					params.put("sex", row.getCell(2).getStringCellValue());
					row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
					params.put("month", row.getCell(3).getStringCellValue());
					row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
					params.put("di", row.getCell(4).getStringCellValue());
					row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
					params.put("rank", row.getCell(5).getStringCellValue());
				}
				dao.deleteIcdAgeSexMonthDiease();
				insertAgeSexMonthDiease(params, user);
			}
		}
		read.close();
		return ReturnUtil.success();
	}

	/**
	 * 导出数据
	 * 
	 * @param resp
	 * @param status
	 *            1-season_weather，2-weather_disease，3-age_sex_month_disease
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public void exportData(HttpServletResponse resp, int status)
			throws IOException {
		List<?> dataList = dao.selectListToExport(status);
		if (dataList == null || dataList.size() == 0) {
			return;
		}
		if (status == 1) {
			Workbook workbook = new XSSFWorkbook(); // 创建文档
			Sheet sheet = workbook.createSheet(); // 创建Sheet
			RespHeaderUtil.setXlsxResp(resp, "season_weather");
			int i = 0;
			for (IcdSeasonWeather line : (List<IcdSeasonWeather>) dataList) {
				Row row = sheet.createRow(i);
				Cell cell1 = row.createCell(0);
				cell1.setCellValue(line.getSeason());
				Cell cell2 = row.createCell(1);
				cell2.setCellValue(line.getDisease());
				Cell cell3 = row.createCell(2);
				cell3.setCellValue(line.getPriority());
				Cell cell4 = row.createCell(3);
				cell4.setCellValue(line.getAge());
				i++;
			}
			OutputStream os = resp.getOutputStream();
			workbook.write(os);
			os.close();
			workbook.close();
		} else if (status == 2) {
			Workbook workbook = new XSSFWorkbook(); // 创建文档
			Sheet sheet = workbook.createSheet(); // 创建Sheet
			RespHeaderUtil.setXlsxResp(resp, "weather_disease");
			int i = 0;
			for (IcdWeatherDisease line : (List<IcdWeatherDisease>) dataList) {
				Row row = sheet.createRow(i);
				Cell cell1 = row.createCell(0);
				cell1.setCellValue(line.getSeason());
				Cell cell2 = row.createCell(1);
				cell2.setCellValue(line.getRuleType());
				Cell cell3 = row.createCell(2);
				cell3.setCellValue(line.getSubType());
				Cell cell4 = row.createCell(3);
				cell4.setCellValue(line.getValue());
				Cell cell5 = row.createCell(4);
				cell5.setCellValue(line.getDisease());
				Cell cell6 = row.createCell(5);
				cell6.setCellValue(line.getPriority());
				Cell cell7 = row.createCell(6);
				cell7.setCellValue(line.getAge());
				Cell cell8 = row.createCell(7);
				cell8.setCellValue(line.getTips());
				i++;
			}
			OutputStream os = resp.getOutputStream();
			workbook.write(os);
			os.close();
			workbook.close();
		} else if (status == 3) {
			Workbook workbook = new XSSFWorkbook(); // 创建文档
			Sheet sheet = workbook.createSheet(); // 创建Sheet
			RespHeaderUtil.setXlsxResp(resp, "age_sex_month_disease");
			int i = 0;
			for (IcdAgeSexMonthDiease line : (List<IcdAgeSexMonthDiease>) dataList) {
				Row row = sheet.createRow(i);
				Cell cell1 = row.createCell(0);
				cell1.setCellValue(line.getAge1());
				Cell cell2 = row.createCell(1);
				cell2.setCellValue(line.getAge2());
				Cell cell3 = row.createCell(2);
				cell3.setCellValue(line.getSex());
				Cell cell4 = row.createCell(3);
				cell4.setCellValue(line.getMonth());
				Cell cell5 = row.createCell(4);
				cell5.setCellValue(line.getDi());
				Cell cell6 = row.createCell(5);
				cell6.setCellValue(line.getRank());
				i++;
			}
			OutputStream os = resp.getOutputStream();
			workbook.write(os);
			os.close();
			workbook.close();
		}
	}

	/**
	 * 添加一条数据
	 * 
	 * @param status
	 *            1-season_weather，2-weather_disease，3-age_sex_month_disease
	 * @param param
	 * @param user
	 * @return
	 */
	public ReturnData addData(int status, Map<String, String> param, User user) {
		if (status == 1) {
			if (medicineDao.selectIcdDiseaseCountByName(param.get("disease")) == 0) {
				Map<String, Object> map = new HashMap<>();
				ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				returnCode.setDesc("导入失败，" + param.get("disease")
						+ "  在疾病维表中不存在");
				return new ReturnData(returnCode, map);
			}
			this.insertSeasonWeather(param, user);
		} else if (status == 2) {
			if (medicineDao.selectIcdDiseaseCountByName(param.get("disease")) == 0) {
				Map<String, Object> map = new HashMap<>();
				ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				returnCode.setDesc("导入失败，" + param.get("disease")
						+ "  在疾病维表中不存在");
				return new ReturnData(returnCode, map);
			}
			this.insertWeatherDisease(param, user);
		} else if (status == 3) {
			if (medicineDao.selectIcdDiseaseCountByName(param.get("di")) == 0) {
				Map<String, Object> map = new HashMap<>();
				ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				returnCode.setDesc("导入失败，" + param.get("di") + "  在疾病维表中不存在");
				return new ReturnData(returnCode, map);
			}
			this.insertAgeSexMonthDiease(param, user);
		}
		return ReturnUtil.success();
	}

	/**
	 * 插入一条 季节天气
	 * 
	 * @param param
	 * @param user
	 */
	private void insertSeasonWeather(Map<String, String> param, User user) {
		IcdSeasonWeather entity = new IcdSeasonWeather();
		entity.setSeason(param.get("season"));
		entity.setDisease(param.get("disease"));
		entity.setPriority(Integer.valueOf(param.get("priority")));
		entity.setAge(param.get("age"));
		entity.setModifierId(user.getUserId());
		entity.setModifierName(user.getRealName());
		dao.insertIcdSeasonWeather(entity);
	}

	/**
	 * 插入一条 季节疾病
	 * 
	 * @param param
	 * @param user
	 */
	private void insertWeatherDisease(Map<String, String> param, User user) {
		IcdWeatherDisease entity = new IcdWeatherDisease();
		entity.setSeason(param.get("season"));
		entity.setRuleType(param.get("ruleType"));
		entity.setSubType(param.get("subType"));
		entity.setValue(Integer.valueOf(param.get("value")));
		entity.setDisease(param.get("disease"));
		entity.setPriority(Integer.valueOf(param.get("priority")));
		entity.setAge(param.get("age"));
		entity.setTips(param.get("tips"));
		entity.setModifierId(user.getUserId());
		entity.setModifierName(user.getRealName());
		dao.insertIcdWeatherDisease(entity);
	}

	/**
	 * 插入一条 年龄性别月份疾病
	 * 
	 * @param param
	 * @param user
	 */
	private void insertAgeSexMonthDiease(Map<String, String> param, User user) {
		IcdAgeSexMonthDiease entity = new IcdAgeSexMonthDiease();
		entity.setAge1(Integer.valueOf(param.get("age1")));
		entity.setAge2(Integer.valueOf(param.get("age2")));
		entity.setSex(Integer.valueOf(param.get("sex")));
		entity.setMonth(Integer.valueOf(param.get("month")));
		entity.setDi(param.get("di"));
		entity.setRank(Integer.valueOf(param.get("rank")));
		entity.setModifierId(user.getUserId());
		entity.setModifierName(user.getRealName());
		dao.insertIcdAgeSexMonthDieaser(entity);
	}
}
